package com.example.Utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.example.model.Menu;
import com.example.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class ImageUploadUtil {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    String bucketName = "yuhuatai0";

    private static final Logger logger = LoggerUtils.getLogger(ImageUploadUtil.class);
    public String uploadBase64Image(String base64Image,String imageName,Integer restaurantId) {
        // 解码Base64图片
        byte[] imageBytes = Base64.getDecoder().decode(base64Image.replaceAll("data:image/jpeg;base64,", ""));
        String pinyin = ToPinyinUtil.toPinyin(imageName);
        String fileName = restaurantId + "_" + pinyin + ".jpg";

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 上传文件到OSS
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(imageBytes));


        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
        // 返回文件名
        return fileName;
    }
    public String getUrl(String fileName) {
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
    public List<Menu> generatePresignedUrl(List<Menu> menus) throws MalformedURLException {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        for (Menu menu : menus) {
            //https://yuhuatai0.oss-cn-beijing.aliyuncs.com/265573b9-e3a0-4e28-8aa7-94c6951b95de.jpg
            String dishImageName = menu.getDishImage();
            String url = getUrl(dishImageName);
            URL parsedUrl = new URL(url);
            String objectName = parsedUrl.getPath().substring(1); // 提取对象名称，去掉前导斜杠
            // 生成签名URL
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 设置URL的有效期为1小时
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
            generatePresignedUrlRequest.setExpiration(expiration);
            URL signedUrl = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
            menu.setDishImage(signedUrl.toString());
        }
        ossClient.shutdown();
        // 获取图片的访问路径
        return menus;
    }

    public void deleteImage(String imageUrl) throws MalformedURLException {
        String url1 = getUrl(imageUrl);
        // 解析URL
        URL url = new URL(url1);
        String host = url.getHost();

        // 提取存储桶名称和endpoint
        String[] hostParts = host.split("\\.");
        String bucketName = hostParts[0]; // 存储桶名称
        logger.info("bucketName:{}",bucketName);
        String endpoint = hostParts[1] + "." + hostParts[2] + "." + hostParts[3]; // endpoint
        logger.info("endpoint:{}",endpoint);
        String objectName = url.getPath().substring(1); // 提取对象名称，去掉前导斜杠
        logger.info("objectName:{}",objectName);
        // 创建OSS客户端实例
        OSS ossClient = new OSSClientBuilder().build("https://" + endpoint, accessKeyId, accessKeySecret);

        // 删除OSS中的对象
        ossClient.deleteObject(bucketName, objectName);

        // 关闭OSS客户端
        ossClient.shutdown();
    }
}
